var express = require('express'); //引入框架
var db = require('./db.js')
var route = express.Router();

var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})

route.post("/saveAddress", urlencodedParser, function (req, res) {
    var {
        name,
        mobile,
        area,
        detail,
        openid
    } = req.body
    var sql = `insert into address(name,mobile,area,detail,openid)values ('${name}','${mobile}','${area}','${detail}','${openid}')`
    db.doMysql(sql).then(data => {
        res.send(db.postText(data))
    })
})

route.post("/updataAddress", urlencodedParser, function (req, res) {
    var {
        id,
        name,
        mobile,
        area,
        detail,
    } = req.body
    var sql = `update address set name='${name}', mobile='${mobile}', area='${area}', detail='${detail}' where id = '${id}' `

    db.doMysql(sql).then(data => {
        res.send(db.postText(data))
    })
})

route.post('/updataMoren', urlencodedParser, function (req, res) {
    let {
        oldId,
        newId
    } = req.body
    var sql1 = `update address set moren=0 where id = '${oldId}' `
    var sql2 = `update address set moren=1 where id = '${newId}' `

    Promise.all([db.doMysql(sql1), db.doMysql(sql2)])
        .then(data => {
            res.send(db.postText(data))
        })
})

route.get('/getAddress', function (req, res) {
    var sql = `select * from address where openid='${req.query.openid}'`

    db.doMysql(sql).then(data => {
        res.send(db.backText(data))
    })
})
route.get('/getAddressItem', function (req, res) {
    var sql = `select * from address where id='${req.query.id}'`

    db.doMysql(sql).then(data => {
        res.send(db.backText(data))
    })
})

route.get('/deleteAddress', function (req, res) {
    var sql = `delete from address where id in (${req.query.id})`
    db.doMysql(sql).then(data => {
        res.send(db.delText(data))
    })
})




exports.route = route